using Microsoft.Extensions.DependencyInjection;
using TangLiveRecorder.Controls;
using TangLiveRecorder.Extensions;
using TangLiveRecorder.Services;

namespace TangLiveRecorder
{
    internal static class Program
    {
        // 定义全局服务提供器
        public static IServiceProvider ServiceProvider { get; private set; }

        /// <summary>
        ///  The main entry point for the application.
        /// </summary>
        [STAThread]
        private static void Main()
        {
            ApplicationConfiguration.Initialize();

            // 配置服务
            var serviceCollection = new ServiceCollection();
            ConfigureServices(serviceCollection);

            // 构建服务提供器
            ServiceProvider = serviceCollection.BuildServiceProvider();
            App.ScopedProvider = ServiceProvider;

            // 初始化数据持久化
            InitializeDataPersistence();

            // 启动轮询服务
            StartPollingService();

            // 数据持久化完成后立即执行一次轮询
            //ExecutePollingOnce();

            var mainForm = ServiceProvider.GetRequiredService<MainWindow>();
            Application.Run(mainForm);
        }

        // 配置服务注册
        private static void ConfigureServices(IServiceCollection services)
        {
            services.AddServices();
        }

        // 初始化数据持久化
        private static void InitializeDataPersistence()
        {
            try
            {
                var persistenceService = ServiceProvider.GetRequiredService<DataPersistenceService>();

                // 初始化文件数据持久化
                Data.InitializeFilePersistence(persistenceService);

                // 初始化直播数据持久化
                Data.InitializeLivePersistence(persistenceService);

                // 初始化设置数据持久化
                Data.InitializeSettingPersistence(persistenceService);

                Data.AddLog("数据持久化服务初始化完成");
            }
            catch (Exception ex)
            {
                Data.AddLog($"数据持久化服务初始化失败: {ex.Message}");
            }
        }

        // 启动轮询服务
        private static void StartPollingService()
        {
            try
            {
                var pollingService = ServiceProvider.GetRequiredService<PollingService>();
                pollingService.Start();
                Data.AddLog("轮询服务启动完成");
            }
            catch (Exception ex)
            {
                Data.AddLog($"轮询服务启动失败: {ex.Message}");
            }
        }

        // 执行一次轮询
        private static void ExecutePollingOnce()
        {
            try
            {
                var pollingService = ServiceProvider.GetRequiredService<PollingService>();
                pollingService.ExecuteOnce();
                Data.AddLog("手动轮询执行完成");
            }
            catch (Exception ex)
            {
                Data.AddLog($"手动轮询执行失败: {ex.Message}");
            }
        }
    }
}